package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.UserMapper;
import aiku.numericalcontroloa.Mapper.WorkSummaryMapper;
import aiku.numericalcontroloa.Model.Entity.BaseEntity;
import aiku.numericalcontroloa.Model.Entity.User;
import aiku.numericalcontroloa.Model.Entity.WorkSummary;
import aiku.numericalcontroloa.Model.Vo.UserScoreCountVo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import aiku.numericalcontroloa.Model.Entity.UserScore;
import aiku.numericalcontroloa.Service.UserScoreService;
import aiku.numericalcontroloa.Mapper.UserScoreMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 马
* @description 针对表【user_score】的数据库操作Service实现
* @createDate 2024-03-13 17:25:47
*/
@Service
public class UserScoreServiceImpl extends ServiceImpl<UserScoreMapper, UserScore>
    implements UserScoreService{
    @Autowired
    private UserScoreMapper userScoreMapper;
    @Autowired
    private WorkSummaryMapper workSummaryMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result addUserScore(String userId, Integer score) {
        String userid = StpUtil.getLoginId().toString();
//        if(userid.equals(userId)){
//            return Result.error(201,"不能给自己评分");
//        }
        //通过id查询是否有改用户存在
        LocalDate today = LocalDate.now();
        LocalDateTime startDateTime = LocalDateTime.of(today, LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(today, LocalTime.MAX);
        LambdaQueryWrapper<WorkSummary> queryWrapper1 = new LambdaQueryWrapper<WorkSummary>()
                .eq(WorkSummary::getUserId, userId)
                .between(WorkSummary::getWorkTime, startDateTime, endDateTime);

        WorkSummary workSummary = workSummaryMapper.selectOne(queryWrapper1);
        if (workSummary == null) {
            return Result.error(201,"该用户还未提交今日总结");
        }

        //查询今天是否已经给该用户评过分
        LambdaQueryWrapper<UserScore> queryWrapper = new LambdaQueryWrapper<UserScore>()
                .eq(UserScore::getUserId, userid)
                .eq(UserScore::getWorkId, workSummary.getWorkId())
                .between(UserScore::getScoreTime, startDateTime, endDateTime);
        UserScore userScore = userScoreMapper.selectOne(queryWrapper);
        if(userScore!=null){
            return Result.error(201,"今天已经给该用户评过分了");
        }
        //这个数没有评分,则给该用户评分
        UserScore scoreOne = new UserScore();
        scoreOne.setWorkId(workSummary.getWorkId());
        scoreOne.setScoreTime(new Date());
        scoreOne.setUserId(userid);
        scoreOne.setScore(score);
        int i = userScoreMapper.insert(scoreOne);
        return i>0?Result.success("评分成功"):Result.error(201,"评分失败");
    }

    /**
     * 通过输入天数统计谁的分数最高,和平均分
     * @param day
     * @return
     */
    @Override
    public Result selectUserScoreList(Integer day) {
        //TODO权限还未做
        //查询所有用户每日总结.查询出来之后,day用户传入的最近天数,比如3,就是3天前的用户每日总结,截止到现在
        LocalDate today = LocalDate.now();
        LocalDateTime startDateTime = LocalDateTime.of(today.minusDays(day), LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(today, LocalTime.MAX);
        LambdaQueryWrapper<WorkSummary> queryWrapper = new LambdaQueryWrapper<WorkSummary>()
                .between(WorkSummary::getWorkTime, startDateTime, endDateTime);
        List<WorkSummary> workSummaryList = workSummaryMapper.selectList(queryWrapper);
        if (workSummaryList.size()<=0){
            List<UserScoreCountVo> userScoreCountVoList = new ArrayList<>();
            return Result.success(userScoreCountVoList);
        }
        //通过用户id来把所有用户每日总结的分数叠加
        Map<String, Integer> scoreMap = new HashMap<>();
        for (WorkSummary workSummary : workSummaryList) {
            Integer integer = scoreMap.get(workSummary.getUserId());
            if (integer==null){
                scoreMap.put(workSummary.getUserId(), workSummary.getScore());
            }else{
                scoreMap.put(workSummary.getUserId(), integer+workSummary.getScore());
            }
        }
        //把map的key转换成list
        List<String> userIdList = scoreMap.keySet().stream().sorted().collect(java.util.stream.Collectors.toList());
        //去用户表查询这些用户信息
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>().in(BaseEntity::getId, userIdList));
        if (userList.size()<=0){
            return Result.success("查询成功",scoreMap);
        }

        List<UserScoreCountVo> userScoreCountVoList = new ArrayList<>();
        for (User user : userList) {
            UserScoreCountVo scoreCountVo = new UserScoreCountVo();
            scoreCountVo.setUserName(user.getNickName());
            scoreCountVo.setUserId(user.getId());
            scoreCountVo.setScore(scoreMap.get(user.getId()));
            userScoreCountVoList.add(scoreCountVo);
        }
        //根据分数大小排序,大的靠前
        userScoreCountVoList = userScoreCountVoList.stream().sorted((o1, o2) -> o2.getScore().compareTo(o1.getScore())).collect(Collectors.toList());
        return Result.success(userScoreCountVoList);
    }
}




